<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/8/11
 * Time: 11:58
 */

namespace App\Http\Controllers\Web;


use App\Models\Administrator;
use App\Models\Role;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;

class LoginController extends BaseController
{

    public function login()
    {
        $username = trim($this->request->post('username',''));
        $password = trim($this->request->post('password',''));
        if(!$username){
            return Response()->json(['code'=>201,'msg'=>'请输入用户名']);
        }
        if(!$password){
            return Response()->json(['code'=>201,'msg'=>'请输入密码']);
        }
        $info = Administrator::with(['roles'])->where('username',trim($username))->where('status',1)->first();

        if(!$info) return Response()->json(['code'=>201,'msg'=>'该用户不存在或者已被禁用']);
        if(!Hash::check($password,$info->password)){
            return Response()->json(['code'=>201,'msg'=>'密码输入错误']);
        }
        $token = setToken($info->username);
        $roles = $info->roles->toArray();
        $permissions = [];
        if($roles) {
            $roleIds = array_column($roles, 'id');
            $permissions = $this->getPermission($roleIds);
        }
        $data = [
            'id'            => $info->id,
            'username'      => $info->username,
            'status'        => $info->status,
            'permissions'   => $permissions
        ];
        Cache::add($token,$data,30 * 3600 * 24);
        $info->remember_token = $token;
        $info->save();
        return Response()->json(['code'=>200,'msg'=>'登录成功','data'=>['token'=>$token,'permissions'=>$permissions]]);

    }
    
    public function loginOut()
    {
        $token = $this->request->header('token');
        $cacheMember = Cache::get($token);
        if(!$cacheMember){
            return Response()->json(['code'=>202,'msg'=>'登录过期，请重新登录！']);
        }
        $memberInfo = Administrator::where('remember_token',trim($token))->first();
        if($memberInfo){
            $memberInfo->remember_token = '';
            $memberInfo->save();
        }
        Cache::forget($token);
        return Response()->json(['code'=>200,'msg'=>'退出成功！']);
        
    }








}
